#include "spi.h"

void SPI2_WriteNSS(uint8_t BitVal)
{
    GPIO_WriteBit(SPI2_PORT, SPI2_NSS_PIN, (BitAction)BitVal);
}
void SPI2_Start(void)
{
    SPI2_WriteNSS(0);
}
void SPI2_Stop(void)
{
    SPI2_WriteNSS(1);
}

void SPI2_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    SPI_InitTypeDef SPI_InitStructure;
    //
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
    //
    GPIO_InitStructure.GPIO_Pin = SPI2_MISO_PIN;  // PB14
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 输入
    GPIO_Init(SPI2_PORT, &GPIO_InitStructure);
    //
    GPIO_InitStructure.GPIO_Pin = SPI2_MOSI_PIN | SPI2_SCK_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // PB13|15 复用推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(SPI2_PORT, &GPIO_InitStructure);
    //
    GPIO_InitStructure.GPIO_Pin = SPI2_NSS_PIN; // NSS只有一个
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(SPI2_PORT, &GPIO_InitStructure);

    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;                        // 主机spi
    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;   // 双线全双工
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;                    // 8bit
    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;                   // 高位先发
    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128; // 36/128
    SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;                          //
    SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;                         //
    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;                            // 软件NSS
    SPI_InitStructure.SPI_CRCPolynomial = 7;                             //
    SPI_Init(SPI2, &SPI_InitStructure);
    SPI_Cmd(SPI2, ENABLE); // 使能SPI2
    SPI2_WriteNSS(1);      // 默认不选从机
}

void SPI2_SetSpeed(uint8_t SPI_BaudRatePrescaler)
{
    SPI2->CR1 &= 0xFFC7; // 1111 1111 1100 0111   bit[3~5]清零
    SPI2->CR1 |= SPI_BaudRatePrescaler;
    SPI_Cmd(SPI2, ENABLE);
}

uint8_t SPI2_SwapByte(uint8_t b)
{
    while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) != SET)
        ;

    SPI_I2S_SendData(SPI2, b); // 写入数据 ,清除SPI_I2S_FLAG_TXE

    while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) != SET)
        ;

    return SPI_I2S_ReceiveData(SPI2); // 接收数据 ,清除SPI_I2S_FLAG_RXNE
}
